//
//  WBMainViewController.swift
//  WCKweibo
//
//  Created by wukai on 17/2/25.
//  Copyright © 2017年 wuchunkai. All rights reserved.
//

import UIKit

class WBMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUpChildrenControllers()
        setupComposeButton()
        
    }
    
    //MARK: --- 私有空间
    //撰写按钮
    lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    
}

// MARK: -- 设置界面
extension WBMainViewController {

    ///设置撰写按钮
     func setupComposeButton(){
    
        tabBar.addSubview(composeButton)
        // 计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        // 将向内缩进的宽度
        let w = tabBar.bounds.width / count - 1 //减1 是将内缩进的宽度减少，能够让按钮的宽度变大，盖住容错点，防止穿帮    
        
        // CGRectInset 正数向内缩进，负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
//
    
    }
    
    
    //设置所有的子控制器
       func setUpChildrenControllers() {
    
        //获取沙河的 json 路径
        let docDri = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDri as NSString).appendingPathComponent("main.json")
        
        //加载data
        var data = NSData(contentsOfFile: jsonPath)
        
        //判断沙河里面是否有内容，没有的话从本地加载文件
        if data == nil {
            //从bundle加载配置的json
           let path = Bundle.main.path(forResource: "main.json", ofType: nil)
           
            data = NSData(contentsOfFile: path!)
        }
        
        //data 一定有内容，反序列化
    
        guard  let array = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as? [[String: AnyObject]] else {
            return
        }
        
    
        ///设置所有的控制器，界面的创建都是依赖网络的json
/*
        let array: [[String: AnyObject]] = [
        
            ["clsName": "WBHomeViewController", "title": "首页", "imageName": "home","visitorInfo": ["imageName": "","message": "关注一些人，回这里看看有什么惊喜"]
             ],
            
            ["clsName": "WBMessageViewController", "title": "消息", "imageName": "message_center", "visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登陆后，别人评论你的微博，发给你的消息，会在这里收到通知"]
            ],
             
            ["clsName": "UIViewController"],
                
            ["clsName": "WBDiscoverViewController", "title": "发现", "imageName": "discover", "visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登录后，最新最热的微博尽在掌握中"]
                ],
                
            ["clsName": "WBProfileViewController", "title": "我的", "imageName": "profile", "visitorInfo": ["imageName": "visitordiscover_image_profile", "message": "登录后你的微博，你的相册、个人信息都会显示在这里"]
                ],
                
            ]
 
        //测试数据是否正确 - 装换成 plist 数据更加直观
//        (array as NSArray).write(toFile: "/Users/wu1/Desktop/demo.json", atomically: true)
       
        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        (data as NSData).write(toFile: "/Users/wu1/Desktop/demo.json", atomically: true)
    */
        
        var arryM = [UIViewController]()
        
        for dict in array! {
            
            arryM.append(Controller(dict: dict as [String : AnyObject]))
            
        }
        
        viewControllers = arryM

    }
    
    private func Controller(dict: [String: AnyObject]) -> UIViewController{
        
        //1.获取字典的内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
        let visitorDict = dict["visitorInfo"] as? [String: String]
            
        else {
            
            return UIViewController()
            
        }
        
        //2.创建视图控制器
        //2.1将clsName 转换成 cls
       let vc = cls.init()
        
        vc.title = title
        //访客视图信息字典赋值
        vc.visitorInfoDictionary = visitorDict
        
        // 3. 设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        //4.设置字体的颜色
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        //5.设置字体的大小
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: UIControlState(rawValue:0))
        //设置导航控制器 实例化控制器的时候，会调用push的方法rootvc 压栈
        let nav = WBNavViewController(rootViewController: vc)
        
      return nav
        
    }

}










